<template>
  <div class="container">
    <div class="search-main">
      <el-form ref="queryRef" :inline="true" :model="queryParams" label-width="68px">
        <el-form-item label="租户名称" prop="name">
          <el-input v-model="queryParams.name" clearable placeholder="请输入租户名称" style="width: 200px"
                    @keyup.enter="handleQuery"/>
        </el-form-item>

        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="queryParams.contacts" clearable placeholder="请输入联系人" style="width: 200px"
                    @keyup.enter="handleQuery"/>
        </el-form-item>

        <el-form-item label="联系电话" prop="iphone">
          <el-input v-model="queryParams.iphone" clearable placeholder="请输入联系电话" style="width: 200px"
                    @keyup.enter="handleQuery"/>
        </el-form-item>

        <el-form-item label="租户状态" prop="iuse">
          <el-select v-model="queryParams.iuse" clearable placeholder="租户状态" style="width: 200px">
            <el-option :key="1" :value="1" label="正常">正常</el-option>
            <el-option :key="0" :value="0" label="停用">停用</el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button icon="Search" size="" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" size="" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-row class="">
      <el-col :span="24">
        <el-button icon="Plus" plain size="" type="primary" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
      <template #iuse="{ row }">
        <el-tag :disable-transitions="true" :type="row.iuse ? 'primary' : 'danger'">{{
            row.iuse ? '正常' : '停用'
          }}
        </el-tag>
      </template>

      <template #edit_iuse="{ row }">
        <el-switch v-model="row.iuse" :active-value="1" :disable-transitions="true"
                   :inactive-value="0"></el-switch>
      </template>

      <template #action="{ row }">
        <template v-if="hasEditStatus(row)">
          <el-button size="" type="primary" @click="saveRowEvent(row)">保存</el-button>
          <el-button size="" @click="cancelRowEvent()">取消</el-button>
        </template>
        <template v-else>
          <el-button plain size="" type="primary" @click="editRowEvent(row)">编辑</el-button>
          <el-popconfirm title="确实要删除当前项吗?" @confirm="deleteRow(row)">
            <template #reference>
              <el-button color="#ff4444f7" plain size="" type="primary" @click="">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </template>
    </vxe-grid>

    <!-- 添加或修改岗位对话框 -->
    <el-dialog v-model="state.dialogVisible" :before-close="handleDialogBeforeClose" :close-on-click-modal="false"
               append-to-body
               title="新增租户" width="500">
      <el-form ref="menuRef" :model="form" :rules="rules" class="dislog-label-item" label-width="80">
        <el-form-item label="租户名称" prop="name">
          <el-input v-model="form.name" class="dislog-label-item" placeholder="请输入租户名称"/>
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" class="dislog-label-item" placeholder="请输入联系人"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="iphone">
          <el-input v-model="form.iphone" class="dislog-label-item" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" class="dislog-label-item" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="租户状态" prop="iuse">
          <el-switch v-model="form.iuse" :active-value="1" :inactive-value="0" active-text="正常" inactive-text="停用"
                     inline-prompt/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(menuRef)">确 定</el-button>
          <el-button @click="cancel(menuRef)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="TenantList" setup>
import {onMounted, reactive, ref, toRefs} from "vue";
import * as TenantApi from "@/api/tenantApi";
import {ElMessage} from "element-plus";

const gridRef = ref();
const queryRef = ref(null);
const menuRef = ref();
const {log} = console;

//组件状态
const state = reactive({
  dialogVisible: false,
  form: {
    name: '',
    iuse: 1,
    iphone: '',
    contacts: '',
    address: '',
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contacts: null,
    name: null,
    iphone: null,
    iuse: null,
  },
  rules: {
    name: [{required: true, message: "租户名称不能为空", trigger: "blur"}],
  },
});

const {queryParams, form, rules} = toRefs(state);

//add
async function submitForm(formEl) {
  console.log(formEl, menuRef);
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = await TenantApi.tenantSave(form.value);
      if (res.code == 200 && res.data) {
        ElMessage.success("操作成功");
        handleQuery();
      }
      cancel(formEl);
    }
  })

}

function cancel(formEl) {
  state.dialogVisible = false;
  reset(formEl);
}

//表格配置
const gridOptions = reactive({
  minHeight: 0,
  emptyText: "暂无数据！",
  keepSource: true,
  headerRowClassName: "table-head-cla",
  border: true,
  showOverflow: true,
  loading: false,
  align: "center",
  headerAlign: 'center',
  rowConfig: {
    isCurrent: true,
    isHover: true,
    keyField: 'id',
  },
  size: "small",
  autoResize: true,
  columnConfig: {
    isHover: true,
    resizable: false,
  },
  editConfig: {
    showIcon: false, //是否显示列头编辑图标
    trigger: "manual",
    showStatus: true,
    autoClear: true,
    mode: "row",
  },
  pagerConfig: {
    border: true,
    enabled: true,
    currentPage: 1,
    pageSize: 10,
    total: 0,
    layouts: [
      "Home",
      "PrevJump",
      "PrevPage",
      "Number",
      "NextPage",
      "NextJump",
      "End",
      "Sizes",
      "FullJump",
      "Total",
    ],
  },
  columns: [{field: "name", title: "租户名称", sortable: true, editRender: {name: "VxeInput"}, align: 'left'},
    {field: "contacts", title: "联系人", sortable: false, editRender: {name: "VxeInput"}},
    {field: "iphone", title: "联系电话", sortable: false, editRender: {name: "VxeInput"}},
    {field: "address", title: "租户地址", sortable: false, editRender: {name: "VxeInput"}},
    {field: "iuse", title: "状态", sortable: false, editRender: {}, slots: {default: 'iuse', edit: 'edit_iuse'},},
    {field: "createByUserName", title: "创建人"},
    {field: "createTime", title: "创建日期", sortable: true},
    {field: "updateByUserName", title: "修改人"},
    {field: "lastModifyTime", title: "修改日期", sortable: true},
    {title: "操作", slots: {default: "action"}},
  ],
  data: [],
});

//分页事件
const gridEvents = {
  pageChange({pageSize, currentPage}) {
    gridOptions.pagerConfig.currentPage = currentPage;
    gridOptions.pagerConfig.pageSize = pageSize;
    queryParams.value.pageNum = currentPage;
    queryParams.value.pageSize = pageSize;
    handleQuery(queryParams);
  },
};

function handleDialogBeforeClose(done) {
  reset(menuRef.value);
  done()
}

function handleAdd() {
  state.dialogVisible = true;
}

//查询list
async function handleQuery() {
  gridOptions.loading = true;
  let res = await TenantApi.tenantSearch(queryParams.value);
  gridOptions.data = res.data.records;
  gridOptions.pagerConfig.total = res.data.total;
  gridOptions.loading = false;
}

/** 提交表单重置 */
function reset(formEl) {
  if (!formEl) return;
  formEl.resetFields()
}

//搜索表单重置
function resetQuery() {
  queryRef.value.resetFields();
  handleQuery();
}

const hasEditStatus = (row) => {
  const $grid = gridRef.value;
  if ($grid) {
    return $grid.isEditByRow(row);
  }
};

const editRowEvent = (row) => {
  const $grid = gridRef.value;
  if ($grid) {
    $grid.setEditRow(row);
  }
};

//编辑用户
const saveRowEvent = async (row) => {
  const $grid = gridRef.value;
  if ($grid) {
    $grid.clearEdit().then(async () => {
      let res = await TenantApi.tenantSave(row);
      if (res.code == 200 && res.data) {
        ElMessage.success("操作成功");
        handleQuery();
      }

    })
  }

};

//编辑取消
const cancelRowEvent = (row) => {
  const $grid = gridRef.value;
  if ($grid) {
    $grid.clearEdit().then(() => {
      // 还原行数据
      $grid.revertData(row);
    });
  }
};

//删除数据
async function deleteRow(row) {
  let res = await TenantApi.tenantDel(row.id);
  if (res.code == 200 && res.data) {
    ElMessage.success("操作成功");
    handleQuery();
  }
}

onMounted(() => {
  handleQuery();


  let da = [
    {
      id: '10',
      name: '用户查询',
      parentId: '2',
    },
    {
      id: '11',
      name: '用户新增',
      parentId: '2',
    },
    {
      id: '10',
      name: '用户查询',
      parentId: '1',
    },

    {
      id: '2',
      name: '角色管理',
      parentId: '-99999',
    },
    {
      id: '1',
      name: '用户管理',
      parentId: '-99999',
    },


  ]
});

</script>

<style lang="scss" scoped>
.container {
  .search-main {
    line-height: 78px;

    .el-form-item {
      margin-bottom: 0px;
    }
  }

  .el-row {
    margin-bottom: 10px;
  }
}
</style>
